#include <iostream>
#include <string>
#include <mysql/mysql.h>
#include <socket.hpp>
using namespace std;
const string host = "127.0.0.1";
const string user = "X";
const string passwd = "Mht1412.";
const string db_name = "test";

int main()
{
    MYSQL *mysql = mysql_init(nullptr);
    if (!mysql)
    {
        cerr << "初始化失败" << endl;
        return 1;
    }
    if (!mysql_real_connect(mysql, host.c_str(), user.c_str(), passwd.c_str(), db_name.c_str(), 3306, nullptr, 0))
    {
        cerr << "数据库连接失败" << endl;
        return 2;
    }
    cout << "数据库连接成功" << endl;
    string sql = "select * from person";
    if (mysql_query(mysql, sql.c_str()))
    {
        cerr << "数据库操作失败" << endl;
        return 3;
    }
    cout << "数据库操作成功" << endl;
    // 获取查询结果
    MYSQL_RES *res = mysql_store_result(mysql);
    // 获取查询结果行列数
    unsigned int rows = mysql_num_rows(res);
    unsigned int fields = mysql_num_fields(res);
    // 获取查询结果列名
    MYSQL_FIELD *fifld = mysql_fetch_fields(res);
    for (int i = 0; i < fields; ++i)
    {
        cout << fifld[i].name << "\t";
    }
    cout << endl;
    for (int i = 0; i < rows; ++i)
    {
        // 依次获取查询结果中行信息
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < fields; ++j)
        {
            cout << row[j] << "\t";
        }
        cout << endl;
    }
    // 释放查询结果
    mysql_free_result(res);
    mysql_close(mysql); // 关闭MySQL

    return 0;
}